package com.sunday.aomi.ui.order;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.sunday.common.adapter.CommenAdapter;
import com.sunday.common.adapter.ViewHolder;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.event.EventBus;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.SpannalbeStringUtils;
import com.sunday.common.utils.StringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.ClearEditText;
import com.sunday.common.widgets.NoScrollListview;
import com.sunday.common.widgets.taosty.Toasty;
import com.sunday.aomi.R;
import com.sunday.aomi.base.BaseApp;
import com.sunday.aomi.event.UpdateCart;
import com.sunday.aomi.ui.mine.address.AddressListActivity;

import com.sunday.member.entity.addr.Address;
import com.sunday.member.entity.order.OrderConfirm;
import com.sunday.member.entity.order.OrderItem;
import com.sunday.member.entity.order.OrderProduct;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/5/26.
 */

public class OrderConfirmActivity extends BaseActivity {

    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.user_name)
    TextView userName;
    @Bind(R.id.user_mobile)
    TextView userMobile;
    @Bind(R.id.linearlayout)
    LinearLayout linearlayout;
    @Bind(R.id.user_addr)
    TextView userAddr;
    @Bind(R.id.select_img)
    ImageView selectImg;
    @Bind(R.id.address_layout)
    RelativeLayout addressLayout;
    @Bind(R.id.list_view)
    NoScrollListview listView;
    @Bind(R.id.total_money)
    TextView totalMoney;
    @Bind(R.id.edit_remark)
    ClearEditText editRemark;
    @Bind(R.id.total_money_bottom)
    TextView totalMoneyBottom;
    @Bind(R.id.confirm_pay)
    Button confirmPay;
    @Bind(R.id.bottom_layout)
    RelativeLayout bottomLayout;

    private OrderConfirm orderConfirm;
    private CommenAdapter<OrderProduct> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_confirm);
        ButterKnife.bind(this);
        title.setText("确认订单");
        orderConfirm = (OrderConfirm) getIntent().getSerializableExtra("orderConfirm");
        initView();
        getDefaultAddr();
    }

    private void initView() {
        if (orderConfirm == null) {
            return;
        }
        if (TextUtils.isEmpty(orderConfirm.getSendAddress())) {
            userName.setText("暂无收货地址");
            userAddr.setText("请选择收货地址");
        } else {
            userAddr.setText(orderConfirm.getSendAddress());
        }
        totalMoney.setText(String.format("￥%s", orderConfirm.getPayAmount().setScale(2,RoundingMode.HALF_UP)));
        totalMoneyBottom.setText(SpannalbeStringUtils.setTextColor("总金额：", mContext.getResources().getColor(R.color.black_6)));
        totalMoneyBottom.append(SpannalbeStringUtils.setTextColor(String.format("￥%s", orderConfirm.getPayAmount().setScale(2, RoundingMode.HALF_UP)),
                mContext.getResources().getColor(R.color.price_yellow)));
        if (orderConfirm.getProducts() != null && !orderConfirm.getProducts().isEmpty()) {
            adapter = new CommenAdapter<OrderProduct>(mContext, orderConfirm.getProducts(), R.layout.list_order_confirm_product) {
                @Override
                public void convert(ViewHolder helper, OrderProduct item, int position) {
                    bind(helper, item);
                }
            };
            listView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }

    }

    private void bind(ViewHolder helper, OrderProduct item) {
        ImageView imageView = helper.getView(R.id.product_img);
        if (!TextUtils.isEmpty(item.getImage())) {
            Picasso.with(mContext)
                    .load(item.getImage())
                    .error(R.mipmap.ic_default)
                    .resize(150, 150)
                    .into(imageView);
        }
        ((TextView) helper.getView(R.id.product_title)).setText(item.getName());
        ((TextView) helper.getView(R.id.product_price)).setText(String.format("￥%s", item.getPrice().setScale(2, RoundingMode.HALF_UP)));
        ((TextView) helper.getView(+R.id.product_num)).setText(String.format("X%d", item.getNum()));
        ((TextView) helper.getView(R.id.product_spec)).setText("规格:"+item.getStandard());
    }

    private Address address;

    private void getDefaultAddr() {
        String nonce = MD5Utils.random();
        long memberId = BaseApp.getInstance().getMember().getId();
        String[] str1 = new String[]{"nonce"};
        String[] str2 = new String[]{nonce};
        showLoadingDialog(0);
        Call<ResultDO<List<Address>>> call = MemberClient.getApiAdapter().getAddrList(nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<List<Address>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Address>>> call, Response<ResultDO<List<Address>>> response) {
                if (isFinish) {
                    return;
                }
                dissMissDialog();
                ResultDO<List<Address>> resultDO = response.body();
                if (resultDO == null) {
                    return;
                }
                if (resultDO.getCode() == 0) {
                    if (resultDO.getResult() == null) {
                        return;
                    }
                    if (resultDO.getResult() != null && !resultDO.getResult().isEmpty()) {
                        address = resultDO.getResult().get(0);
                        setAddr(address);
                    }
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Address>>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private final static int REQUEST_ADDR = 0x1111;

    @OnClick({R.id.confirm_pay, R.id.address_layout})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.confirm_pay:
                if (address == null) {
                    Toasty.error(mContext, "请选择收货地址").show();
                    return;
                }
                creatOrder();
                break;
            case R.id.address_layout:
                intent = new Intent(mContext, AddressListActivity.class);
                intent.putExtra("isSelectMode", true);
                startActivityForResult(intent, REQUEST_ADDR);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_ADDR:
                address = (Address) data.getSerializableExtra("address");
                setAddr(address);
                break;
        }
    }

    private void setAddr(Address address) {
        if (address == null) {
            userName.setText("暂无收货地址");
            userMobile.setText("");
            userAddr.setText("请添加收货地址");
        } else {
            userName.setText("姓名:" + address.getReceiveName());
            userMobile.setText(address.getReceiveMobile());
            userAddr.setText(String.format("%1$s",address.getReceiveAddress()));
        }
    }
private List<String> cartIds=new ArrayList<>();
    private void creatOrder() {
        cartIds.clear();
        if (orderConfirm.getProducts() != null && !orderConfirm.getProducts().isEmpty()) {
            for (OrderProduct item:orderConfirm.getProducts()){
                cartIds.add(String.valueOf(item.getCartId()));
            }
        }
        String nonce = MD5Utils.random();
        String addressId = String.valueOf(address.getId());
        String remark =editRemark.getText().toString();
        String cartIdStr=StringUtils.listToString(cartIds);
        String[] str1=new String[]{"cartIds","addressId","remark","nonce"};
        String[] str2=new String[]{cartIdStr,addressId,remark,nonce};
        showLoadingDialog(0);
        Call<ResultDO<OrderItem>> call= MemberClient.getApiAdapter().createOrder(cartIdStr,null,null,null,address.getId(),null,
                null,remark,nonce,SignUtil.getSign(str1,str2));
        call.enqueue(new Callback<ResultDO<OrderItem>>() {
            @Override
            public void onResponse(Call<ResultDO<OrderItem>> call, Response<ResultDO<OrderItem>> response) {
                if (isFinish||response.body()==null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode()==0){
                    //暂时先不支付 直接跳转采购订单页面
                   //intent=new Intent(mContext,BuyOrderListActivity.class);
                   // startActivity(intent);
                    intent=new Intent(mContext,PaySuccessActivity.class);
                    intent.putExtra("totalMoney",String.format("￥%s", orderConfirm.getPayAmount().setScale(2,RoundingMode.HALF_UP)));
                    intent.putExtra("address",address);
                    startActivity(intent);
                    EventBus.getDefault().post(new UpdateCart());
                    finish();
                }else {
                    Toasty.error(mContext,response.body().getMessage()).show();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<OrderItem>> call, Throwable t) {
                dissMissDialog();
                Toasty.error(mContext,"网络连接错误").show();
            }
        });
    }
}
